package com.uzhie.component;

import com.uzhie.web.dao.GpsDAO;
import com.uzhie.exception.GPSException;
import com.uzhie.jt808.JT808Session;
import com.uzhie.jt808.JT808SessionManager;
import com.uzhie.jt808.msg.entity.JT_0200;
import com.uzhie.web.module.GpsRecord;
import com.uzhie.util.RedisCacheManager;
import org.apache.log4j.Logger;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;
import java.util.List;

import static com.uzhie.util.ConstantKit.REDIS_GPS_KEY;

/**
 * 位置信息组件
 */
@Component
public class GpsComponent {

    private Logger logger = Logger.getLogger(this.getClass());
    @Autowired(required = false)
    private GpsDAO gpsDAO;
    @Autowired(required = false)
    @Qualifier(value = "sessionManager")
    JT808SessionManager sessionManager;
    @Autowired(required = false)
    RedisCacheManager<GpsRecord> redisCacheManager;


    /**
     * 新增定位信息
     *
     * @param order
     */
    public void addGpsRecord(@NotEmpty(message = GPSException.Status.SIM_ERROR) String sim,
                              @NotNull(message = GPSException.Status.ORDER_ERROR) JT_0200 order) {
        JT808Session session = sessionManager.getSession(sim);
        String driver = null;
        if (session != null) driver = session.getDriverName();
        GpsRecord record = GpsRecord.ReadFromOrder(order, sim, driver);
        redisCacheManager.lSet(REDIS_GPS_KEY, record);
    }

    /**
     * 定时获取redis中的位置信息
     */
    public void gpsInsertTask() {
        long size = redisCacheManager.lGetListSize(REDIS_GPS_KEY);
        List<GpsRecord> gpsRecords;
        if (size >500){
            size = 500;
        }
        for (int count = 0; count < size; count += 100) {
            gpsRecords = redisCacheManager.lGet(REDIS_GPS_KEY, count, count + 100 - 1);
            logger.info("从redis中获取到" + size + "条位置，并进行批量入库操作");
            if (gpsRecords != null && gpsRecords.size() > 0) {
                gpsDAO.insertGroup(gpsRecords);
                redisCacheManager.ltrim(REDIS_GPS_KEY, 100, -1);
                long l = redisCacheManager.lGetListSize(REDIS_GPS_KEY);
                logger.info("成功入库" + gpsRecords.size() + "条数据，并从redis中清除 剩余数量 " + l);
            }
        }
    }
}
